﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;

namespace jsweb.ContentTypes
{
   class BinaryContent : ContentProvider
   {
      private Dictionary<string, string> _supportedContentTypes = new Dictionary<string, string>(){
         {".gif", "image/gif"},
         {".png", "image/png"},
         {".jpg", "image/jpeg"},
         {".jpeg", "image/jpeg"}
      };

      /// <summary>
      /// Returns true if the requested content is supported
      /// </summary>
      /// <param name="context"></param>
      /// <returns></returns>
      private bool IsBinaryContent(System.Net.HttpListenerContext context)
      {
         var extension = Path.GetExtension(context.Request.Url.LocalPath);
         if(extension == null)
            return false;
         return _supportedContentTypes.ContainsKey(extension);
      }

      /// <summary>
      /// Handles the content request
      /// </summary>
      /// <param name="context"></param>
      public override bool HandleContent(System.Net.HttpListenerContext context)
      {
         // Check for valid content
         if (!IsBinaryContent(context))
         {
            // Invalid content type, set error
            context.Response.StatusCode = (int)HttpStatusCode.UnsupportedMediaType;
            return false;
         }

         // Read file data
         BinaryWriter binaryWriter = new BinaryWriter(context.Response.OutputStream);
         binaryWriter.Write(File.ReadAllBytes("Views" + context.Request.Url.LocalPath));
         binaryWriter.Flush();

         // Set status OK
         context.Response.StatusCode = (int) HttpStatusCode.OK;
         return true;
      }
   }
}
